package com.woniu51.k15demo.utils;


import com.woniu51.k15demo.entity.Manager;
import io.jsonwebtoken.*;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 杨光
 * @date 2022年02月15日 10:18
 */
public class JwtUtil {

    private static final String secret = "HSL39830@:!1";//密钥

    public static String generateJWT(Manager manager){

        JwtBuilder builder = Jwts.builder();
        Map<String,Object> claims = new HashMap<>();
        claims.put("userId",manager.getId());
        claims.put("userCode",manager.getUserCode());
        claims.put("userName",manager.getUserName());
        //使用对称加密生成jwt token
        builder.setClaims(claims).signWith(SignatureAlgorithm.HS512,secret);
        String jwtToken = builder.compact();
        return jwtToken;
    }

    /**
     *
     * @author jitwxs
     * @date 2022/2/15 0015 10:40
     * @param jwt
     * @return java.util.Map<java.lang.String,java.lang.Object>
     *     如果返回null，说明用户没登录，否则，说明登录过了
     */
    public static Map<String,Object> parseJWT(String jwt){
        Map<String,Object> result = null;

        JwtParser parser = Jwts.parser();
        //如果解析失败，会抛出异常
        try{
            Jws<Claims> claimsJws = parser.setSigningKey(secret).parseClaimsJws(jwt);
            Claims claims = claimsJws.getBody();
            result = new HashMap<>();
            result.put("userId",claims.get("userId"));
            result.put("userCode",claims.get("userCode"));
            result.put("userName",claims.get("userName"));
            return result;
        }catch(Exception e){
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        Manager manager = new Manager();
        manager.setUserCode("0000");
        manager.setId(1L);
        manager.setUserName("admin");

        String jwt = generateJWT(manager);
        System.out.println(jwt);

        jwt=jwt.replace("e","a");
        System.out.println(jwt);

        Map<String, Object> result = parseJWT(jwt);
        System.out.println(result);
    }
}
